﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.IO;
using SQLEditor.admin.entity;
using SQLEditor.dal;

namespace SQLEditor.admin.service
{
    public class SqlQuestionService : BaseService
    {
        public string getall()
        {
            var list = from b in DB.sqlQuestion
                       
                       select new SqlQuestion
                       {
                           id = b.id,
                           title = b.title,
                           refAnswer = b.answer,
                           explain = b.explain,
                           point = b.point,
                           userId = b.userId,
                           projectId = b.sqlProject.id,
                           projectRemark = b.sqlProject.remark,
                       };
            string json = JsonUtil.ToJson(list.ToList());
            return json;
        }

        public string search(int pageSize, int pageIndex, string order, string where)
        {
            int totalCount = 0;
            SqlParameter paramTotalCount = new SqlParameter("@totalCount", totalCount);
            paramTotalCount.Direction = ParameterDirection.Output;
            var pager = DB.sqlQuestion.SqlQuery("exec sp_Pager @tableName,@columns,@order,@pageSize,@pageIndex,@where,@totalCount output",
                GetPagerParameters("sqlQuestion", "*", order, where, pageSize, pageIndex, paramTotalCount)).ToList();
            var list = from b in pager
                       
                       select new SqlQuestion
                       {
                           id = b.id,
                           title = b.title,
                           refAnswer = b.answer,
                           explain = b.explain,
                           point = b.point,
                           userId = b.userId,
                           projectId = b.sqlProject.id,
                           projectRemark = b.sqlProject.remark,
                       };
            var l = list.ToList();
            totalCount = Convert.ToInt32(paramTotalCount.Value);
            string json = JsonUtil.ToJson(new { total = totalCount, rows = l });
            return json;
        }

        public string add(sqlQuestion b)
        {
            DB.sqlQuestion.Add(b);
            DB.SaveChanges();
            string json = JsonUtil.ToJson(new { success = true });
            return json;
        }

        public string edit(sqlQuestion b)
        {
            var old = DB.sqlQuestion.FirstOrDefault(m => m.id == b.id);
            old.title = b.title;
            old.answer = b.answer;
            old.explain = b.explain;
            old.point = b.point;
            old.projectId = b.projectId;

            DB.SaveChanges();
            string json = JsonUtil.ToJson(new { success = true });
            return json;
        }

        public string delete(string strIds)
        {
            if (string.IsNullOrEmpty(strIds))
            {
                return JsonUtil.ToJson(new { success = false, msg = "没有选择要删除的记录！" });
            }
            string[] arr = strIds.Split(',');
            List<int> ids = new List<int>();
            foreach (var id in arr)
            {
                ids.Add(int.Parse(id));
            }
            var questions = DB.sqlQuestion.Where(m => ids.Contains(m.id)).ToList();
            if (questions != null)
            {
                questions.ForEach(m => DB.sqlQuestion.Remove(m));
                DB.SaveChanges();
                return JsonUtil.ToJson(new { success = true });
            }
            else
            {
                return JsonUtil.ToJson(new { success = false, msg = "删除失败！" });
            }
        }

        public void import(Stream inputStream, int userId) {
            StreamReader sr = new StreamReader(inputStream, System.Text.Encoding.UTF8);
            string c = sr.ReadToEnd();
            sr.Close();
            string[] lines = c.Split('\n');
            sqlProject prj = null;
            for (int i = 0; i < lines.Length; )
            {
                string line = lines[i];
                if (line == null || line.Trim().Length < 6 || line[0] == '#')
                {
                    i++;
                    continue;
                }
                line = line.Trim();
                if(line.StartsWith("title=")){
                    string title = line.Substring(6);
                    i++;
                    line = lines[i].Trim();                    
                    while(!line.StartsWith("answer="))
                    {
                        if (line.Length > 0){
                            title = title +"\n"+ line;
                        }
                        i++;
                        line = lines[i].Trim();
                    }
                    string answer = line.Substring(7);
                    int j = i + 1;
                    line = lines[j].Trim();
                    while (!line.StartsWith("title="))
                    {
                        if (line.Length > 0)
                        {
                            answer = answer + "\r\n" + line;
                        }
                        j++;
                        if (j >= lines.Length || lines[j]==null) break;    //结束                                      
                        line = lines[j].Trim();
                        
                    }                    
                    sqlQuestion q = new sqlQuestion()
                    {
                        point = 1,
                        userId = userId,
                        addDate = DateTime.Now,   
                        explain = "",
                        sqlProject = prj,
                        title = title,
                        answer = answer
                    };
                    DB.sqlQuestion.Add(q);
                    i = j;
                }
                else if (line.StartsWith("projectName="))
                {
                    string projectName = line.Substring(12).Trim();
                    prj = DB.sqlProject.FirstOrDefault(m=>m.name.Equals(projectName));                   
                    i++;
                }
            }
            DB.SaveChanges();
        }
    }
}